import { IsDate, IsOptional, validateOrReject } from 'class-validator';
import { BeforeInsert, BeforeUpdate, Column, DeleteDateColumn, PrimaryGeneratedColumn } from 'typeorm';

export class CommonEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;
  @Column({
    comment: '创建时间',
    type: 'timestamp',
    nullable: true,
  })
  createAt: Date;
  @Column({
    comment: '创建者',
    nullable: true,
  })
  @IsOptional()
  createBy: string;
  @Column({
    comment: '修改时间',
    type: 'timestamp',
    nullable: true,
  })
  updateAt: Date;
  @Column({
    comment: '修改者',
    nullable: true,
  })
  @IsOptional()
  updateBy: string;

  @Column({
    comment: '删除时间',
    type: 'timestamp',
  })
  @DeleteDateColumn()
  @IsDate()
  @IsOptional()
  deleteAt: Date;
  @Column({
    comment: '删除者',
    nullable: true,
  })
  @IsOptional()
  deleteBy: string;

  @BeforeInsert()
  setCreatedAt(){
    const now = new Date()
    this.createAt = now;
    this.updateAt = now;
  }

  @BeforeUpdate()
  setUpdateAt(){
    this.updateAt = new Date()
  }

  @BeforeInsert()
  async validateBeforeInsert(){
    await validateOrReject(this)
  }

  @BeforeUpdate()
  async validateBeforeUpdate(){
    await validateOrReject(this,{skipMissingProperties:true})
  }
}
